package www.openteam.com.ui;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.OTApplication;
import www.openteam.com.R;
import www.openteam.com.base.BaseActivity;
import www.openteam.com.bean.Download;
import www.openteam.com.bean.UpdateTypeInfo;
import www.openteam.com.contract.SplishDownLoadContract;
import www.openteam.com.presenter.SplishDownloadPresenter;
import www.openteam.com.service.DownloadService;
import www.openteam.com.tool.CreatDialog;
import www.openteam.com.tool.NetworkUtil;
import www.openteam.com.tool.StringTool;
import www.openteam.com.tool.ToastUtil;

/**
 * Created by kylin on 2017/1/19.
 */

public class SplashActivity extends BaseActivity<SplishDownloadPresenter>
        implements SplishDownLoadContract.SplishDownLoadView {

    private static final String TAG = SplashActivity.class.getSimpleName();

    /**
     * Id to identify a camera permission request.
     */
    private static final int REQUEST_CAMERA = 0;
    private static final int REQUEST_STORAGE = 1;
    @Bind(R.id.tv_version)
    TextView tv_version;
    @Bind(R.id.tv_pb)
    TextView tv_pb;
    @Bind(R.id.pb_download)
    ProgressBar pb_download;
    CoordinatorLayout container;
    private ActivityManager am;
    View mLayout;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"};

    private static String[] PERMISSIONS_USE = {
            Manifest.permission.CAMERA,
            Manifest.permission_group.STORAGE
    };


    public static final String MESSAGE_PROGRESS = "message_progress";
    private LocalBroadcastManager bManager;

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(MESSAGE_PROGRESS)) {
                Download download = intent.getParcelableExtra("download");
                pb_download.setProgress(download.getProgress());
                if (download.getProgress() == 100) {
                    ToastUtil.showToast(SplashActivity.this, "文件下载完成!");
                } else {
//                    StringTool.getDataSize(download.getCurrentFileSize())
//                            + "/" +
//                            StringTool.getDataSize(download.getTotalFileSize());
                    tv_pb.setText(StringTool.getDataSize(download.getCurrentFileSize())
                            + "/" +
                            StringTool.getDataSize(download.getTotalFileSize()));
                }
            }
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: " + getVersionName());
        tv_version.setText(tv_version.getText() + getVersionName());
//        tv_name.setText(tv_name.getText() + getVersionName());
        if (Build.VERSION.SDK_INT >= 23) {
            Log.d(TAG, "VERSION: 6");
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                requestCameraPermission();
            }

            //checkPermission();
            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    !=PackageManager.PERMISSION_GRANTED){
                requestStoragePermission();
            }

            if (NetworkUtil.isWifi(OTApplication.getmContext())) {
                mPresenter.queryUpdateInfo(getVc());

            } else {
                final Intent it = new Intent(this, LoginActivity.class); //你要转向的Activity
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        startActivity(it); //执行
                        finish();
                    }
                };
                timer.schedule(task, 1000 * 1); //10秒后
            }

        } else {
            Log.d(TAG, "onCreate: 6");
            if (NetworkUtil.isWifi(OTApplication.getmContext())) {

                mPresenter.queryUpdateInfo(getVc());
                Log.d(TAG, "onCreate: mpresenter");
            } else {
                Log.d(TAG, "onCreate: time");
                final Intent it = new Intent(this, LoginActivity.class); //你要转向的Activity
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        startActivity(it); //执行
                        finish();
                    }
                };
                timer.schedule(task, 300 * 1); //10秒后
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: ");
        if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) &&
                (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        == PackageManager.PERMISSION_GRANTED)
                ) {
            if (NetworkUtil.isWifi(OTApplication.getmContext())) {
                mPresenter.queryUpdateInfo(getVc());

            } else {
                final Intent it = new Intent(this, LoginActivity.class); //你要转向的Activity
                Timer timer = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        startActivity(it); //执行
                        finish();
                    }
                };
                timer.schedule(task, 100 * 1); //10秒后
            }
        }
    }

    private void requestCameraPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale
                (this, Manifest.permission.CAMERA)) {

            Log.d(TAG, "requestCameraPermission: if ");
            Snackbar.make(container, R.string.permission_camera_my
                    , Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityCompat.requestPermissions(SplashActivity.this, new String[]{
                            Manifest.permission.CAMERA
                    }, REQUEST_CAMERA);

                    if (ActivityCompat.checkSelfPermission(SplashActivity.this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        requestStoragePermission();
                    }
                }
            }).show();

        } else {
            Log.d(TAG, "requestCameraPermission: end ");
            ActivityCompat.requestPermissions(
                    SplashActivity.this, new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA);
        }

    }

    private void requestStoragePermission() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            Log.d(TAG, "requestCameraPermission: if ");
            Snackbar.make(container, R.string.permission_storage
                    , Snackbar.LENGTH_INDEFINITE).setAction(R.string.ok, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ActivityCompat.requestPermissions(SplashActivity.this, PERMISSIONS_STORAGE
                            , REQUEST_STORAGE);
                }
            }).show();

        } else {
            Log.d(TAG, "requestSTORAGEPermission: end ");
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_STORAGE);
        }

    }


    @Override
    protected SplishDownloadPresenter loadPresenter() {
        return new SplishDownloadPresenter();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        container = (CoordinatorLayout) findViewById(R.id.container);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        final Intent it = new Intent(this, LoginActivity.class); //你要转向的Activity
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                startActivity(it); //执行
                finish();
            }
        };
        timer.schedule(task, 100 * 1);

        Log.d(TAG, "onRestart: ");
    }


//    @Override
//    protected void onPause() {
//        super.onPause();
//        final Intent it = new Intent(this, LoginActivity.class); //你要转向的Activity
////        startActivity(it); //执行
////        finish();
//        Timer timer = new Timer();
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//                startActivity(it); //执行
//                finish();
//            }
//        };
//        timer.schedule(task, 100 * 1);
//
//        Log.d(TAG, "onpause: ");
//    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    public int getVc() {

        int versonCode = 0;

        PackageManager packageManager = OTApplication.getmContext().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(OTApplication.getmContext().getPackageName(), 0);
            versonCode = packageInfo.versionCode;
            Log.e(TAG, "getVc: "+ versonCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return versonCode;
    }

    @Override
    public void queryUISuccess(UpdateTypeInfo updateTypeInfos) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        builder.create();
        builder.setTitle("更新选项");
        builder.setMessage(updateTypeInfos.getContent());
        builder.setPositiveButton("马上更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Log.d(TAG, "onClick: " + getAvailMemory() + "aaaaa" +
                        Formatter.formatFileSize(getBaseContext(), getAvailMemory()));
                if (getAvailMemory() < 30 * 1024 * 1024) {
                    ToastUtil.showToast(SplashActivity.this, "内存不足");
                    Timer timer = new Timer();
                    final Intent it = new Intent(SplashActivity.this, LoginActivity.class); //你要转向的Activity
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            startActivity(it); //执行
                            finish();
                        }
                    };

                    timer.schedule(task, 1000 * 1); //10秒后

                } else {
                    registerReceiver();
                    Intent intent = new Intent(SplashActivity.this, DownloadService.class);
                    startService(intent);
                }
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                toOtherActivity();
            }
        });

        builder.show();
    }


    @Override
    public void queryUIFail(String failMsg) {

        Log.d(TAG, "queryUIFail: ");
        Timer timer = new Timer();
        final Intent it = new Intent(SplashActivity.this, LoginActivity.class); //你要转向的Activity
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                startActivity(it); //执行
                finish();
            }
        };

        timer.schedule(task, 1000 * 1); //10秒后

    }


    private String getVersionName() {
        String versionName = null;
        PackageManager packageManager = OTApplication.getmContext().getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo(OTApplication.getmContext().getPackageName(), 0);
            versionName = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }


    private void toOtherActivity() {
        Intent intent = new Intent();
        intent.setClass(SplashActivity.this, LoginActivity.class);
        startActivity(intent);
        finish();
    }


    private long getAvailMemory() {// 获取android当前可用内存大小

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        //mi.availMem; 当前系统的可用内存

//        return Formatter.formatFileSize(getBaseContext(), mi.availMem);// 将获取的内存大小规格化
        return mi.availMem;
    }


    private void registerReceiver() {

        bManager = LocalBroadcastManager.getInstance(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MESSAGE_PROGRESS);
        bManager.registerReceiver(broadcastReceiver, intentFilter);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //解除注册时，使用注册时的manager解绑
        if (bManager != null) {
            bManager.unregisterReceiver(broadcastReceiver);
        }
    }


}